package com.wtwd.wtwddevice.service.impl;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtwd.device.constant.DeviceLoginEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.constant.SeparatorConstant;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.device.util.StringUtils;
import com.wtwd.wtwddevice.mapper.DeviceMapper;
import com.wtwd.wtwddevice.model.entity.AppComm;
import com.wtwd.wtwddevice.model.entity.Device;
import com.wtwd.wtwddevice.model.entity.DeviceStatus;
import com.wtwd.wtwddevice.model.entity.Deviceinfo;
import com.wtwd.wtwddevice.service.IAppCommService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IDeviceStatusService;
import com.wtwd.wtwddevice.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2024-05-14
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {


    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private IDeviceStatusService deviceStatusService;

    @Resource
    private IAppCommService appCommService;

    @Resource
    private IRedisService redisService;


    @Override
    public Device getDeviceInfoByImei(String imei) {
        if (StringUtils.isEmpty(imei)) {
            return null;
        }
        return new LambdaQueryChainWrapper<>(deviceMapper)
                .eq(Device::getImei, imei)
                .one();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deviceLogin(String form, WTProtocol protocol) {
        String imei = protocol.getImei();
        Device device = getDeviceInfoByImei(imei);
        if (device == null) {//设备未入库
            return false;
        }
        try {
            String loginBody = protocol.getBody();
            String[] data = loginBody.split(SeparatorConstant.CMD_BODY_SEGMENTATION);
            if (data.length != DeviceLoginEnum.FIELD_NUMBER) return false;//登录报文异常
            DeviceStatus deviceStatus = new DeviceStatus();
            deviceStatus.setDeviceId(device.getId());
            deviceStatus.setStatus(DeviceLoginEnum.DEVICE_ONLINE);
            deviceStatus.setDeviceTime(protocol.getTime());
            deviceStatusService.insertOrUpdate(deviceStatus);
            device.setHost(form);
            device.setIccid(protocol.getIccid());
            device.setIsActivate(Deviceinfo.ACTIVATE);
            device.setDeviceLocationType(data[2]);
            device.setWatchId(data[5]);
            device.setDeviceVersion(data[6]);
            device.setModemDeviceVersion(data[7]);
            updateById(device);
            AppProtocol appProtocol = AppProtocol.builder()
                    .imei(protocol.getImei())
                    .cmdName(MsgTypeEnum.DEVICE_STATE_PUSH.getCmdName())
                    .data(DeviceLoginEnum.DEVICE_ONLINE)
                    .build();
            appCommService.pushDeviceState(device.getId(),appProtocol);
        } catch (Exception e) {
            log.info("协议：{}--登录异常：{}", protocol.toString(), e.getMessage());
            return false;
        }

        return true;
    }

    @Override
    public Long getDeviceIdByImei(String imei) {
        String value = redisService.getValue(DEVICE_KEY_PREFIX + imei);
        if (StringUtils.isEmpty(value)) {
            Device device = getDeviceInfoByImei(imei);
            if (device == null) {
                return null;
            }
            redisService.setKey(DEVICE_KEY_PREFIX + imei, String.valueOf(device.getId()), 0, TimeUnit.SECONDS);
            return device.getId();
        }
        return Long.valueOf(value);
    }

    @Override
    public boolean appLogin(String form, String imei) {
        Device device = getDeviceInfoByImei(imei);
        if (device == null) {//设备未入库
            return false;
        }
        AppComm appComm = new AppComm();
        appComm.setDeviceId(device.getId());
        appComm.setHost(form);
        appComm.setStatus(DeviceLoginEnum.DEVICE_ONLINE);
        appCommService.insertOrUpdate(appComm);
        return true;
    }
}
